package com.jdk.demo.thread.aqs;

import java.util.concurrent.locks.AbstractQueuedSynchronizer;

public class Demo {

	private final Sync sync;

	public Demo() {
        sync = new Sync();
    }

	public static void main(String[] args) {
		Demo d = new Demo();
		Thread t = new Thread(() -> {
			d.lock(1);
			d.unlock(1);
		});
		t.start();
		Thread t2 = new Thread(() -> {
			d.lock(1);
			d.unlock(1);
		});
		t2.start();
		Thread t3 = new Thread(() -> {
			d.lock(10);
			d.unlock(1);
		});
		t3.start();
	}

	private void lock(int acquires) {
		sync.acquire(acquires);
	}

	private void unlock(int acquires) {
		sync.release(acquires);
	}

	static class Sync extends AbstractQueuedSynchronizer {

		private static final long serialVersionUID = 1L;
		private static int count = 0;

		@Override
		protected final boolean tryAcquire(int acquires) {
			final Thread current = Thread.currentThread();
			int c = getState();
            // state是0，锁处于空闲状态，使用CAS获取
            if (c == 0) {
                if (compareAndSetState(0, acquires)) {
	                // 获取成功后，当前线程就是锁的持有者
                    setExclusiveOwnerThread(current);
                    return true;
                }
            }
            return false;
        }

		@Override
		protected final boolean tryRelease(int releases) {
			setState(0);
			return true;
		}

	}

}
